<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <link rel="stylesheet" type="text/css" href="../css/aui.2.0.css" />
    <style>
        table {
            border: 1px solid #e0e0e0;
            border-collapse: collapse;
        }

        td {
            border: 1px solid #e0e0e0;
        }
    </style>
</head>

<body>
    <header class="aui-bar aui-bar-nav main-header">
        <a class="aui-pull-left aui-btn" tapmode onclick="closeWin();">
            <span class="aui-iconfont aui-icon-left"></span>
        </a>
        <div class="aui-title" id="middle">
            备货
        </div>
    </header>
    <div class="aui-bar aui-bar-nav sub-header"></div>
    <div class="aui-content aui-margin-b-15" style="margin-top:50px;padding-bottom: 50px;">
        <div class="white_background">
            <ul class="aui-list aui-form-list">
                <li class="aui-list-item">
                    <div class="aui-list-item-inner">
                        <span class="aui-input-addon"
                            style="width:30%;text-align: left;font-weight: 600;font-size: 0.8rem;">箱号扫描:</span>
                        <input type="text" class='aui-input' placeholder="" style="width: 70%;" id="scanCode" />
                        <i class="aui-input-addon aui-iconfont aui-icon-scan " style="font-size: 1.6rem"
                            onclick="doScan()"></i>
                    </div>
                </li>
            </ul>


            <div style="background-color:white; height: 10rem;width: 100%;">
                <p id="planQty" style="font-size:0.9rem;color: #1abc9c;"></p>
                <p id="countQtySum" style="font-size:0.9rem;color: #1abc9c;"></p>
                <div style="height:9rem;overflow-y:auto;">
                    <table class="table" style='width:100%;' id="table">
                        <thead>
                            <tr style="text-align: center;color: #757575;font-size: 12px;font-weight: bold;">
                                <td algin='center' style="width:120px;;">物料号</td>
                                <td algin='center' style="width:120px;">配送数量</td>
                                <td algin='center' style="width:100px;">批次号</td>
                                <td algin='center' style="width:90px;">源库</td>
                                <td algin='center' style="width:100px;">源库位</td>
                            </tr>
                        </thead>
                        <tbody id="tbodyHtml">
                        </tbody>
                    </table>
                </div>
            </div>
            <p id="countQty" style="font-size:0.9rem;color: #e51c23;padding-top: 4px;height: 1.5rem;"></p>
        </div>

        <ul class="ui-selectee" id="tbodyHtmlS">

        </ul>


        <div style="padding-top:5%;"></div>
        <div class="aui-btn aui-btn-info aui-btn-block" onclick="save()" id="submitButton">提交</div>

    </div>


</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="../script/aui-list-swipe.js"></script>
<script type="text/javascript" src="../script/public.js"></script>
<script type="text/javascript" src="../script/clickThrottle.js"></script>
<script type="text/javascript">
    //光标所在id
    var idSelector = "";
    var scanRule = ""; //条码解析规则
    var mrlCode = ""; //物料编码
    var mrlName = "";//物料名称
    var paTaskCode = "";
    var arrSave = [];
    var num = 0;
    var mrlnum = 0;
    var arrTaskCode = ""

    var swipe = new ListSwipe();
    var planQty = 0;
    var countQty = 0;
    apiready = function () {
        paTaskCode = api.pageParam.paTaskCode;
        mrlCode = api.pageParam.mrlCode;
        mrlName = api.pageParam.mrlName;

        $("#scanCode").focus();
        idSelector = "scanCode";

        var title = "备货-" + mrlName;
        document.getElementById("middle").innerHTML = title;

        getPaTaskDetailInfo(paTaskCode, mrlCode);
        getPaDistributeMrlRels(paTaskCode, mrlCode);

        //查询条码解析规则
        initScanRule();
    };

    // 扫描配送任务号
    function doScan() {
        var moduleScanner = api.require('moduleScanner');
        var params = {
            top: 150,//扫描窗口的上边距
            width: 250,//扫描窗口的宽
            height: 250,//扫描窗口的高
            useColor: false,//是否使用自己设定的颜色(startColor和endColor),
            //如果不使用设定的颜色就使用默认的那张网格图
            startColor: '#0F08C8FF',//渐变起始颜色
            endColor: '#7F08C8FF',//渐变结束颜色
            animTime: 2200,//扫描动画时间,单位为毫秒
        };
        moduleScanner.toScannerActivityForResult(params, function (ret, err) {
            //解析条码
            tmSplit(ret);
        });
    }
    //查询扫描规则
    function initScanRule() {
        var serverUrl = localStorage.getItem('serverUrl');
        var un = localStorage.getItem("un");
        var url = serverUrl + "/app/getTmScanRule";
        var data = {
            values: {
                un: un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == '0') {
                    scanRule = myobj.scanRule
                } else {
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            }
        });
    }
    /*   //扫描回车事件
      $("#scanCode").on('keypress', function (e) { //#keyword为input文本框
          var keycode = e.keyCode;
          var sm = $(this).val();
          if (keycode == '13') {
              console.log("回车事件");
              $("#scanCode").val(sm);
              tmSplit(sm);
          }
      }); */
    //监听回车事件
    $("#scanCode").on('keypress', function (e) { //#keyword为input文本框
        if (!clickThrottle()) {
            $("#scanCode").val("");
            return;
        }
        var keycode = e.keyCode;
        var tm = $(this).val();
        $("#scanCode").val("");
        if (keycode == '13') {
            if (tm != null && tm != "" && tm != undefined) {
                tmSplit(tm);
            }
        }
    });

    //扫描之后条码解析
    function tmSplit(sm) {
        $("#tm").val(sm);
        //直接解析
        if (scanRule == "old") {

            //本地解析
            localAnalyze(sm);
        } else {

            //后台解析
            postAnalyze(sm);
        }
    }
    //本地解析
    function localAnalyze(sm) {
        var arr = sm.split(",");
        if (arr[1] == null || arr[1] == undefined) {
            $("#mrlCode").val("");
        } else {
            $("#mrlCode").val(arr[1]);
        }
        if (arr[2] == null || arr[2] == undefined) {
            $("#qty").val("");
        } else {
            $("#qty").val(arr[2]);
        }
        if (arr[3] == null || arr[3] == undefined) {
            $("#lotCode").val("");
        } else {
            $("#lotCode").val(arr[3]);
        }
        if (arr[4] == null || arr[4] == undefined) {
            $("#tmID").val("");
        } else {
            $("#tmID").val(arr[4]);
        }
        if (arr[9] == null || arr[9] == undefined) {
            $("#boxnum").val("");
        } else {
            $("#boxnum").val(arr[9]);
        }

        var mrlCode = arr[1];
        var qty = arr[2];
        var lotCode = arr[3];
        var boxnum = arr[9];
        var tmId = arr[4];
        if (api.pageParam.mrlCode == mrlCode) {
            saveAuto(sm, mrlCode, lotCode, qty, boxnum, tmID);
        } else {
            api.toast({
                msg: "物料号不匹配！",
                duration: 3000
            });
        }


    }

    //后台解析条码
    function postAnalyze(sm) {
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/analysisBarCodeCommon";
        var data = {
            values: {
                tm: sm, //条码
                un: un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                //成功
                if (myobj.code == '0') {

                    var map = myobj.data;
                    for (var key in map) {
                        $("#" + key).val(map[key]);
                    }
                    var mrlCode = map["mrlCode"];
                    var qty = map["qty"];
                    var lotCode = map["lotCode"];
                    var boxnum = map["boxnum"];
                    var tmId = map["tmID"];
                    if (api.pageParam.mrlCode == map["mrlCode"]) {
                        saveAuto(sm, mrlCode, lotCode, qty, boxnum, tmId);
                    } else {
                        api.toast({
                            msg: "物料号不匹配！",
                            duration: 3000
                        });
                    }
                } else if (myobj.code == '1') {

                    $("#boxnum").val("");
                    $("#boxnum").select();
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            } else {
                alert(JSON.stringify(err));
            }
        });
    }




    function closeWin() {
        api.closeWin();
        api.execScript({
            name: 'paAndonDistribute',
            script: 'getDistributeMrlInfo("' + api.pageParam.paTaskCode + '");'
        });
    }
    // 获取-对应的 配送任务明细信息
    function getPaTaskDetailInfo(paTaskCode, mrlCode) {
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/searchPaTaskDetailInfo";

        var params = new Object();
        params.url = url;
        params.method = 'post';
        params.dataType = 'json';
        var un = localStorage.getItem('un');
        var data = {
            values: {
                paTaskCode: paTaskCode,
                mrlCode: mrlCode,
                un: un
            }
        };
        api.showProgress({
            title: '保存中...',
        });
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                api.hideProgress();
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                //返回成功
                if (myobj.code == "0") {
                    var list = myobj.list;
                    var taskList = myobj.taskList;
                    planQty = myobj.planqty;
                    var html = "";
                    //遍历
                    for (var i = 0; i < list.length; i++) {
                        html += "<tr style='text-align: center;color: black;font-size: 10px;' >";
                        html += "<td name='mrlCode'>" + mrlCode + "</td>";
                        html += "<td name='planqty'>" + list[i].planQty + "</td>";
                        html += "<td name='uda2n'>" + list[i].ext17 + "</td>";
                        // html += "<td name='uda3c'>" + list[i].ext18 + "</td>";
                        html += "<td name='uda4c'>" + (list[i].ext19 == null ? "" : list[i].ext19) + "</td>";
                        html += "<td name='uda4n'>" + (list[i].ext20 == null ? "" : list[i].ext20) + "</td>";
                        html += "</tr>";
                    }
                    for (var i = 0; i < taskList.length; i++) {
                        arrTaskCode = taskList[i].task_code + ','
                    }

                    $api.html($api.byId("tbodyHtml"), html);
                    $api.html($api.byId("planQty"), "计划数量：" + planQty);

                } else if (myobj.code == "1") {
                    //失败
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            }
        });

    }
    function getPaDistributeMrlRels(paTaskCode, mrlCode) {
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/searchPaDistributeMrlRels";

        var params = new Object();
        params.url = url;
        params.method = 'post';
        params.dataType = 'json';
        var un = localStorage.getItem('un');
        var data = {
            values: {
                paTaskCode: paTaskCode,
                mrlCode: mrlCode,
                un: un
            }
        };

        api.showProgress({
            title: '保存中...',
        });
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                api.hideProgress();
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                //返回成功
                if (myobj.code == "0") {
                    var list = myobj.list;
                    countQty = myobj.countQty;
                    $api.html($api.byId("countQtySum"), "已备货数量：" + countQty);

                } else if (myobj.code == "1") {
                    //失败
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            }
        });
    }

    //自动保存
    function saveAuto(sm, mrlCode, lotCode, qty, boxnum, tmID) {
        //判断箱号是否重复
        for (var i = 0; i < arrSave.length; i++) {
            if (boxnum == arrSave[i].boxnum) {
                api.toast({
                    msg: '箱号已存在！',
                    duration: 3000
                });
                return;
            }
        }
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getWorkCellByBoxnum";
        var data = {
            values: { ////以表单方式提交参数（JSON对象）
                un: un,
                boxnum: boxnum,
                tm: sm,
                mrlCode: mrlCode,

            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            //   $("#boxnum").attr('disabled', false);
            //   $("#boxnum").select();
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                //成功
                if (myobj.code == '0') {
                    num = num + 1;
                    mrlnum = mrlnum + parseInt(qty);
                    $api.html($api.byId("countQty"), "当前备货数量" + mrlnum);
                    if (Number(mrlnum) >= Number(planQty)) {
                        //若备货数量>=计划数量，则改变字体颜色为绿色
                        $api.html($api.byId("countQty"), "当前备货数量" + mrlnum + " （已满足）");
                        document.getElementById("countQty").style.color = "#1abc9c";
                    } else {
                        $api.html($api.byId("countQty"), "当前备货数量" + mrlnum + " （未满足）");
                        document.getElementById("countQty").style.color = "#e51c23";
                    }
                    var model = {
                        mrlCode: mrlCode, //物料号
                        lotCode: lotCode, //批次号
                        qty: qty, //转移数量
                        tm: sm, //箱号
                        boxnum: boxnum, //条码
                        tmID: tmID, //条码ID
                        drawing: myobj.drawing,
                        mrlName: myobj.mrlName
                    }
                    arrSave.push(model);
                    setTable(arrSave);

                } else if (myobj.code == '1') {

                    api.hideProgress();
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            }
        });

    }

    function setTable(list) {
        var html = "";
        for (var i = 0; i < list.length; i++) {
            html += "<li class='sortable ui-selectee ui-sortable'>";
            html += "<div class='white_background'>"
            html += "<ul class='aui-list aui-media-list ui-selectee'>";
            html += "<li class='aui-list-item  ui-selectee' style='background-color:#addbef !important;'>";

            html += "<div class='aui-media-list-item-inner ui-selectee'>";
            html += "<div class='aui-list-item-inner ui-selectee'>";

            html += "<div class='aui-list-item-text ui-selectee' style='height: 25px;'>";
            html += "<div class='aui-list-item-label ui-selectee list-tr-title'>箱号</div>";
            html += "<div class='aui-list-item-inner ui-selectee'  style='font-size:0.65rem;'>" + list[i].boxnum + "</div>";
            html += "</div>";
            html += "<div class='aui-list-item-text ui-selectee' style='height: 25px;'>";
            html += "<div class='aui-list-item-label ui-selectee list-tr-title'>物料编码</div>";
            html += "<div class='aui-list-item-inner ui-selectee' style='font-size:0.65rem;'>" + list[i].mrlCode + "</div>";
            html += "</div>";
            html += "<div class='aui-list-item-text ui-selectee' style='height: 25px;'>";
            html += "<div class='aui-list-item-label ui-selectee list-tr-title'>规格</div>";
            html += "<div class='aui-list-item-inner ui-selectee' style='font-size:0.65rem;'>" + list[i].drawing + "</div>";
            html += "</div>";
            html += "<div class='aui-list-item-text ui-selectee' style='height: 25px;'>";
            html += "<div class='aui-list-item-label ui-selectee list-tr-title'>物料名称</div>";
            html += "<div class='aui-list-item-inner ui-selectee' style='font-size:0.65rem;'>" + list[i].mrlName + "</div>";
            html += "</div>";
            html += "<div class='aui-list-item-text ui-selectee' style='height: 25px;'>";
            html += "<div class='aui-list-item-label ui-selectee list-tr-title'>批次</div>";
            html += "<div class='aui-list-item-inner ui-selectee' style='font-size:0.65rem;'>" + list[i].lotCode + "</div>";
            html += "</div>";
            html += "<div class='aui-list-item-text ui-selectee' style='height: 25px;'>";
            html += "<div class='aui-list-item-label ui-selectee list-tr-title'>数量</div>";
            html += "<div class='aui-list-item-inner ui-selectee' style='font-size:0.65rem;'>" + list[i].qty + "</div>";
            html += "</div>";
            html += "<div class='aui-list-item-text ui-selectee' style='height: 15px;'>";
            html += "<div class='aui-list-item-label ui-selectee list-tr-title'></div>";
            html += "<div class='aui-list-item-inner ui-selectee'></div>";
            html += "<div class='aui-list-item-right aui-btn ui-selectee' style='background:red;color:#f5f5f5;' onclick='remove(\"" + list[i].boxnum + "\");'>移除</div>";
            html += "</div>";

            html += "</div>";
            html += "</div>";
            html += "</li>";
            html += "</ul>";
            html += "</div>";
            html += "</li>";
        }
        $api.html($api.byId("tbodyHtmlS"), html);
    };
    function remove(boxnum) {
        for (var i = 0; i < arrSave.length; i++) {
            if (arrSave[i].boxnum == boxnum) {
                num = num - 1;
                mrlnum = mrlnum - parseInt(arrSave[i].qty);
                arrSave.splice(i, 1)
                // $api.html($api.byId("countQty"), "当前备货数量" + mrlnum);
                if (Number(mrlnum) >= Number(planQty)) {
                    //若备货数量>=计划数量，则改变字体颜色为绿色
                    $api.html($api.byId("countQty"), "当前备货数量" + mrlnum + " （已满足）");
                    document.getElementById("countQty").style.color = "#1abc9c";
                } else {
                    $api.html($api.byId("countQty"), "当前备货数量" + mrlnum + " （未满足）");
                    document.getElementById("countQty").style.color = "#e51c23";
                }
                setTable(arrSave);
            }

        }

    };

    function removeAll(list) {
        mrlnum = 0
        for (var j = 0; j < list.length; j++) {
            mrlnum += parseInt(list[j].qty);
            //          $api.html($api.byId("countQty"), "当前备货数量" + mrlnum);
            if (Number(mrlnum) >= Number(planQty)) {
                //若备货数量>=计划数量，则改变字体颜色为绿色
                $api.html($api.byId("countQty"), "当前备货数量" + mrlnum + " （已满足）");
                document.getElementById("countQty").style.color = "#1abc9c";
            } else {
                $api.html($api.byId("countQty"), "当前备货数量" + mrlnum + " （未满足）");
                document.getElementById("countQty").style.color = "#e51c23";
            }
        }
        setTable(list);
        arrSave = list;
    };


    // 保存箱号信息
    function save() {
        if (arrSave.length == 0) {
            api.toast({
                msg: "没有可保存的数据",
                duration: 3000
            });
            return;
        }
        const submitButton = document.getElementById('submitButton');
        submitButton.style.pointerEvents = "none"

        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/saveTaskMrl";
        var params = new Object();
        params.url = url;
        params.method = 'post';
        params.dataType = 'json';
        var un = localStorage.getItem('un');
        var data = {
            values: {
                paTaskCode: arrTaskCode,
                mrlCode: mrlCode,
                mrlName: mrlName,
                list: JSON.stringify(arrSave),
                un: un
            }
        };
        api.showProgress({
            title: '保存中...',
        });
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                api.hideProgress();
                submitButton.style.pointerEvents = "auto"
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                //返回成功
                if (myobj.code == "0") {
                    api.toast({
                        msg: "保存成功",
                        duration: 3000
                    });
                    var number = countQty + mrlnum;
                    $api.html($api.byId("countQtySum"), "已备货数量：" + number);
                    $api.html($api.byId("tbodyHtmlS"), "");
                    $api.html($api.byId("countQty"), "当前备货数量" + 0);
                    arrSave = [];
                    mrlnum = 0;
                } else if (myobj.code == "1") {
                    if (myobj.list != undefined && myobj.list != null) {
                        removeAll(myobj.list);
                    }
                    //失败
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            } else {
                api.hideProgress();
                submitButton.style.pointerEvents = "auto"
            }
        });

    }


</script>

</html>